package by.jtraining.london.service.impl;

import java.security.NoSuchAlgorithmException;

import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.jtraining.london.model.User;

import by.jtraining.london.repo.UserRepository;
import by.jtraining.london.service.UserService;
import by.jtraining.london.service.UtilService;

import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

public class UserServiceImpl extends
		GenericServiceImpl<User, Long, UserRepository> implements UserService {
	
	private static final Logger LOG = LoggerFactory
			.getLogger(UserServiceImpl.class);
	
	@Inject
	public UserServiceImpl(UserRepository userRepository) {
		super(userRepository);
	}

	@Transactional
	@Override
	public User getUserByLoginAndPassword(String login, String password) {
		LOG.debug("Try get user by login ({}) and password ({})",login,password);
		try {
			String hashPass = UtilService.stringToHash(password);
			return repo.getUserByLoginAndPassword(login, hashPass);
		} catch (NoSuchAlgorithmException e) {
			LOG.debug("Can not get hash password!", e);
			return null;
		} catch (NoResultException e){
			return null;
		}
	}

	@Transactional
	@Override
	public User getUserByLogin(String login) {
		LOG.debug("Try get user by login ({})",login);
		return repo.getUserByLogin(login);
	}

	@Transactional
	@Override
	public boolean changePassword(String login, String password) {
		LOG.debug("Try change user's password (login={})",login);
		try {
			String hashPass = UtilService.stringToHash(password);
			repo.changePassword(login, password);
			User user = getUserByLogin(login);
			if (user.getPasswordHash() == hashPass) {
				LOG.debug("User's password chenged!");		
				return true;
			} else {
				LOG.debug("User's password don't chenged!");	
				return false;
			}
		} catch (NoSuchAlgorithmException e) {
			LOG.debug("Can not get hash for new password!", e);	
			return false;
		}
	}

}
